Page({
    data: {
        userInfo: {}
    },
    onLoad() {
        // 从本地存储中获取用户信息
        const userInfo = wx.getStorageSync('userInfo');
        if (userInfo) {
            this.setData({
                userInfo
            });
        }
    },
    onChooseAvatar(e) {
        const { avatarUrl } = e.detail;
        this.setData({
            'userInfo.avatarUrl': avatarUrl
        });
    },
    onNicknameInput(e) {
        this.setData({
            'userInfo.nickName': e.detail.value
        });
    },
    saveUserInfo() {
        const userInfo = this.data.userInfo;
        // 上传头像到云存储（如果不是默认头像且不是云存储路径）
        const uploadAvatar = () => {
            return new Promise((resolve, reject) => {
                const defaultAvatarUrl = '/images/avatar.png';
                if (userInfo.avatarUrl === defaultAvatarUrl || userInfo.avatarUrl.startsWith('cloud://')) {
                    resolve(userInfo.avatarUrl);
                    return;
                }
                const cloudPath = `avatars/${userInfo.openid}-${Date.now()}.jpg`;
                wx.cloud.uploadFile({
                    cloudPath,
                    filePath: userInfo.avatarUrl,
                    success: res => resolve(res.fileID),
                    fail: err => {
                        console.error('上传头像失败：', err);
                        resolve(defaultAvatarUrl);
                    }
                });
            });
        };
        // 上传头像并保存用户信息
        uploadAvatar()
           .then(avatarFileID => {
                // 更新头像地址
                userInfo.avatarUrl = avatarFileID;
                // 存储更新后的用户信息
                wx.setStorageSync('userInfo', userInfo);
                wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                });
                // 延迟返回上一页，让用户看到成功提示
                setTimeout(() => {
                    wx.navigateBack({
                        delta: 1
                    });
                }, 1500);
            })
           .catch(err => {
                console.error('保存用户信息出错：', err);
                wx.showToast({
                    title: '保存失败，请重试',
                    icon: 'none',
                    duration: 2000
                });
            });
    }
});